# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include "Header.h"
# include "MountVFS.h"
# include "vfs_errorcodes.h"
# include "NArrayTree.h"
# include "BinarySearchTree.h"
# include "Hashing.h"

struct NArray_node *mountNArray (struct VFS *header, struct NArray_node *NArrayRoot) {
	int i;
	for (i = 0; i < MAX_FD_SIZE; i++) {
		if(header -> freeList[i]) {
			NArrayRoot = insertNArrayNode(NArrayRoot, header -> fd[i].filePath);
		} 
	}
	return NArrayRoot;
}

void displayNArray (struct NArray_node *NArrayRoot) {
	printf("\nPre Order NArray Tree:\n");
	preOrder1 (NArrayRoot);
	printf("\nIn Order NArray Tree:\n");
	inOrder1 (NArrayRoot);
	printf("\nPost Order NArray Tree:\n");
	postOrder1 (NArrayRoot);
}

struct BST_node *mountBST (struct VFS *header, struct BST_node *BSTRoot) {
	int i;
	for (i = 0; i < MAX_FD_SIZE; i++) {
		if(header -> freeList[i]) {
			BSTRoot = insertBSTNode(BSTRoot, header -> fd[i].filePath);
		} 
	}
	return BSTRoot;
}

void displayBST (struct BST_node *BSTRoot) {
	printf("\nPre Order Binary Search Tree:\n");
	preOrder2 (BSTRoot);
	printf("\nIn Order Binary Search Tree:\n");
	inOrder2 (BSTRoot);
	printf("\nPost Order Binary Search Tree:\n");
	postOrder2 (BSTRoot);
}

struct HashNode **mountHashTable (struct VFS *header, struct HashNode **table) {
	struct HashNode **temp;
	int i;
	table = (struct HashNode **) malloc (26 * sizeof(struct HashNode *));
	for (i = 0; i < 26; i++) {
		table[i] = NULL;
	}
	for (i = 0; i < MAX_FD_SIZE; i++) {
		if(header -> freeList[i] && header -> fd[i].fileName[0] != '\0') {
			temp = hash (header -> fd[i].fileName, table);
			*temp = addHashNode (&header -> fd[i], *temp);
		}
	}
	return table;
}

struct VFS *mount_vfs(struct VFS *header, char *name) {
	FILE *fp;
	int i = 0, chk = 0;
	fp = (FILE *) fopen(name,"rb");
	if (fp == NULL) {
		printf("mountvfs_FAILURE ");
		puts(ERR_VFS_MOUNT_01);
		return NULL;
	}
	chk = fread(header, sizeof(header), 1, fp);
	if (chk == 0) {
		printf("mountvfs_FAILURE ");
		puts(ERR_VFS_MOUNT_02);
		fclose(fp);
		return NULL;
	}
	fclose(fp);
	return header;
}
